package cn.enjoyedu.sendtype;

import cn.enjoyedu.config.BusiConst;
import cn.enjoyedu.config.KafkaConst;
import org.apache.kafka.clients.producer.Callback;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.clients.producer.RecordMetadata;
import org.apache.kafka.common.serialization.StringSerializer;

/**
 * @author King老师   享学课堂 https://enjoy.ke.qq.com
 * 类说明：发送消息--异步模式
 */
public class KafkaAsynProducer {

    private static KafkaProducer<String,String> producer = null;

    public static void main(String[] args) {
        /*消息生产者*/
        producer = new KafkaProducer<>(
                KafkaConst.producerConfig(StringSerializer.class,
                        StringSerializer.class));
        /*待发送的消息实例*/
        ProducerRecord<String,String> record;

        /**
         * 成功 或者 异常
         * 只会有一个有值
         */
        Callback callback = (metadata, exception) -> {
            
            //失败
            if (null != exception) {
                exception.printStackTrace();
            }
            
            //成功 :返回生产偏移量
            if (null != metadata) {
                System.out.println("offset:" + metadata.offset() + "-"
                        + "partition:" + metadata.partition());
            }
        };
        try {
            record = new ProducerRecord<>(BusiConst.HELLO_TOPIC, "teacher14", "deer");
            //MARK 也可以给回调函数
            producer.send(record, callback);
        } finally {
            producer.close();
        }
    }




}
